#!/usr/bin/env python
# coding=utf-8
#--------------------------------------------------------------------------
# 文件名:       health_tr.py 
# 说明：        目的、作用说明
#
# 版本：        0.01
# 作者：        xiao
#
# 创建时间：    2011-12-07 
# 许可证：      Apache License V2.0
#--------------------------------------------------------------------------

import Translator as tr
import random
import time
import os
import XiaoTool as xt
from xml.dom.minidom import parseString
import sqlite3DB

## 类注释
#
class health_tr:

	## 方法注释
	#
	#  @param
	#  @return
	#
	def __init__(self, maxid=0, tto="es", tfrom="en", appId="37BD3FF97378CCC15C5BD522BC17D0917949DEBE"):
		self.tto = tto
		self.tfrom = tfrom
		self.appId = appId
		self.maxid = maxid
	#------------------------------------------ End def __init__()


	## 方法注释
	#
	#  @param
	#  @return
	#
	def outDb(self, txt):
		doc = parseString(txt)
		doc_array = doc.getElementsByTagName("TranslatedText")

		strAraay = {}
		for na in doc_array:
			adoc = self.getText(na.childNodes)

			hm = adoc[0]
			try:
				id = str(int(adoc[1:8]))
			except:
				print(adoc[1:8])
				continue

			if id not in strAraay:
				strAraay[id] = {}

			if "id" not in strAraay[id]:
				strAraay[id]["id"] = id

			strAraay[id][hm] = adoc[14:]

		db = sqlite3DB.DbAction("/root/xiaotool/tool/pro_%s.db" % self.tto)
		db.dbLoad()

		features = ""
		price = ""
		for string in strAraay:
			if "1" not in strAraay[string] or "4" not in strAraay[string]:
				continue
			if "2" in strAraay[string]:
				price = ", price='%s'" % strAraay[string]["2"]
			if "3" in strAraay[string]:
				features = ", features='%s'" % strAraay[string]["3"]

			try:
				db.setExec(("UPDATE `product` SET `name`='%s'%s%s, `description`='%s', `flag`=0 WHERE `id`=%s;" % (strAraay[string]["1"], price, features, strAraay[string]["4"], strAraay[string]["id"])).encode("utf8"))
				#open("test.sql", "a").write(("UPDATE `product` SET `name`='%s'%s%s, `description`='%s', `flag`=0 WHERE `id`=%s;\n" % (strAraay[string]["1"], price, features, strAraay[string]["4"], strAraay[string]["id"])).encode("utf8"))
			except:
				xt.setTimeLog(strAraay[string])

		db.actionExec()
		db.dbClose()
	#------------------------------------------ End def outDb()

	## 方法注释
	#
	#  @param
	#  @return
	#
	def fromDb(self):
		db = sqlite3DB.DbAction("/root/xiaotool/tool/pro_%s.db" % self.tto)
		db.dbLoad()
		proSqlQuery = db.query("SELECT id, name, price, features, description FROM `product` WHERE flag=1 AND id > %s ORDER BY `id` ASC LIMIT %s;" % (self.maxid, random.randint(3,15)))
		db.dbClose()

		idss = ""
		stringAraay = []
		for id, name, price, features, description in proSqlQuery:
			intId = int(id)
			stringAraay.append("%s ===== %s" % (10000000+intId, name))
			stringAraay.append("%s ===== %s" % (20000000+intId, price))
			stringAraay.append("%s ===== %s" % (30000000+intId, features))
			stringAraay.append("%s ===== %s" % (40000000+intId, description))

			idss += "%s, " % intId
			if self.maxid < intId:
				self.maxid = intId

		open("/root/xiaotool/tool/maxid", "w").write(str(self.maxid))
		tran = tr.TranslatorBing()
		tran.setOutFunc(self.outDb)
		tran.translator([stringAraay])
	#------------------------------------------ End def fromDb()

	## 方法注释
	#
	#  @param
	#  @return
	#
	def getText(self, nodelist):
		rc = []
		for node in nodelist:
			if node.nodeType == node.TEXT_NODE:
				rc.append(node.data)

		return ''.join(rc)
	#------------------------------------------ End def getText()

	## 方法注释
	#
	#  @param
	#  @return
	#
	def action(self):
		t1 = time.time()
		while True:
			if (time.time() - t1) > 2000:
				break

			if self.maxid > 110000:
				self.maxid = 1

			time.sleep(random.randint(10, 20))
			try:
				self.fromDb()
			except:
				continue
	#------------------------------------------ End def action()


#------------------------------------------------------ End class health_tr()


if __name__ == "__main__":
	os.system('kill -s 9 `pgrep -f "/usr/bin/python /root/xiaotool/tool/health_tr_de.py"`')
	time.sleep(random.randint(300, 1000))
	hr = health_tr(int(open("/root/xiaotool/tool/maxid").read().strip()))
	hr.action()
